package com.example.mymarket.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.mymarket.Data_model.CartItem;
import com.example.mymarket.R;

import java.util.List;

public class CartItemAdapter extends BaseAdapter {

    private Context context;
    private List<CartItem> cartItemList;

    public CartItemAdapter(Context context, List<CartItem> cartItemList) {
        this.context = context;
        this.cartItemList = cartItemList;
    }

    @Override
    public int getCount() {
        return cartItemList.size();
    }

    @Override
    public Object getItem(int position) {
        return cartItemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.cart_item, parent, false);
            holder = new ViewHolder();
            holder.goodsNameTextView = convertView.findViewById(R.id.tv_name);
            holder.priceTextView = convertView.findViewById(R.id.tv_price);
            holder.numberTextView = convertView.findViewById(R.id.tv_date);
            holder.productImgView = convertView.findViewById(R.id.iv_product);
            holder.radioButton = convertView.findViewById(R.id.rb_select);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        CartItem cartItem = cartItemList.get(position);
        holder.goodsNameTextView.setText(cartItem.getGoodsName());
        holder.priceTextView.setText(String.valueOf(cartItem.getPrice()));
        holder.numberTextView.setText(String.valueOf(cartItem.getNumber()));

        Glide.with(context)
                .load(cartItem.getPicUrl())
                .into(holder.productImgView);
        holder.radioButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (holder.radioButton.isChecked()) {
                    // 取消选中状态
                    holder.radioButton.setChecked(false);
                }
            }
        });

        return convertView;
    }

    private static class ViewHolder {
        TextView goodsNameTextView;
        TextView priceTextView;
        TextView numberTextView;
        ImageView productImgView;
        RadioButton radioButton;
    }
}